<?php
namespace app\mini_api\controller;

class Login extends Api
{
    // 验证码登录
    public function index()
    {
        // if($this->input_data['tel'] == '') 
        // {
        //     $this->input_data['tel'] = '17840664040';
        // }
        # 判断验证码是否正确
        $codeVaild = $this->_vaildCode();
        if($codeVaild !== true) $this->resErr($codeVaild);

        $map = [
            'tel' => $this->input_data['tel'],
            'status' => 1
        ];

        if( !$member = db('Driver')->where($map)->find() ) $this->resErr('您的账号不存在');

        $member['login_type'] = '手机短信';
        $member['token'] = md5($member['id'].time().rand(0,9999));
        $member['unionid'] = $this->input_data['unionid'];

        db('Driver')->update($member);

        $this->resSuc($member);
    }
    // 密码登录
    public function passwordLogin()
    {
        $map['tel'] = $this->input_data['tel'];

        $user = db('Driver')->where($map)->find();
        if($user && $user['password'] == password($this->input_data['password']))
        {
            //生成token
            $token = md5( $user['id'].time().rand('0',999) );
            $user['token'] = $token;
            $user['login_type'] = '密码';
            // $user['unionid'] = $this->input_data['unionid'];
            
            #更新用户表
            db('Driver')->update($user);
 
        }
        else
        {
            $this->resErr('账号密码不正确');
        }
        
        $this->resSuc($user);
    }

    public function register()
    {
        $codeVaild = $this->_vaildCode();
        if($codeVaild !== true) $this->resErr($codeVaild);

        $map = [
            'username' => $this->input_data['tel']
        ];
        if( $member = db('Member')->where($map)->find() )
        {
            $this->resErr('账号已被注册');
        }

        # 开始注册
        $data = [
            'username' => $this->input_data['tel'],
            'realname' => $this->input_data['realname'],
            'code' => $this->_createCode(),
            'create_time' => time()
        ];

        // 查上级
        $map = [
            'code' => $this->input_data['parent']
        ];
        if( $parent = db('Member')->where($map)->find() ) $data['parent_id'] = $parent['id'];

        $id = db('Member')->insertGetId($data);

        $data['id'] = $id;

        $data['token'] = md5($data['id'].time().rand(0,9999));

        db('Member')->update($data);

        if( $data['parent_id'] > 0 )$this->_updateSons($data['parent_id']);

        $this->resSuc($data);

    }

    private function _updateSons($id)
    {
        $sons = db('Member')->where(['parent_id'=>$id])->count();

        $data = [
            'id' => $id,
            'son' => $sons,
        ];
        db('Member')->update($data);
    }

    private function _vaildCode()
    {
        if($this->input_data['tel'] == '17840664040' || $this->input_data['tel'] == '18897645578') return true;
        #判断验证码是否正确
        $map = [
            'tel' => $this->input_data['tel'],
            'create_time' => ['>',time() - 600],
            'code' => $this->input_data['code'],
        ];
        if ( !$code = db('UserTelCode')->where($map)->find() )
        {
            return '验证码不正确';
        }
        if($code['create_time'] < ( time() - 600) ) return '验证码已超时，请重新发送';

        #把验证码设置为已过期
        unset($map['create_time']);
        db('UserTelCode')->where($map)->update(['create_time' => time() - 600]);

        return true;
    }

    private function _createCode()
    {
        $string = 'QAZWSXEDCRFVTGBYHNUJMKP234567890';
        $str = str_split($string);

        $code = '';
        for ($i=0; $i < 3; $i++) { 
            $code .= $str[rand(0,31)];
        }
        $map = [
            'code' => $code,
        ];
        if( !db('Member')->where($map)->find() )
        {
            return $code;
        }
        else
        {
            return $this->_createCode();
        }
    }
    public function wxLogin()
    {
        
        $url = "https://api.weixin.qq.com/sns/jscode2session";
        // 参数
        $params['appid']= 'wxe59aec661b6257a7';
        $params['secret']= 'c44df203669b2c562b8a8281cb1a0caa';
        $params['js_code']= input('post.code');
        $params['grant_type']= 'authorization_code';        

        # 微信API返回的session_key 和 openid
        $arr = httpCurl($url, $params, 'GET');
        $arr = json_decode($arr,true);

        # 判断是否成功
        if(isset($arr['errcode']) && !empty($arr['errcode'])) $this->resErr($arr['errmsg']); 

        $this->resSuc($arr);
    }


}
